<template>
  <div class="update-photo">
    <img :src="img" class="img" alt="" ref="img" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: ''
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 视图控制, 1 代表限制裁剪框不能超出图片范围
      dragMode: 'move', // 拖拽图片模式 图片可移动
      aspectRatio: 1, // 设置裁剪框为固定的宽高比
      autoCropArea: 1, // 允许初始化时自动的裁剪图片 配合 data 使用 默认true
      cropBoxMovable: false, // 是否可以拖拽裁剪框 默认true
      cropBoxResizable: false, // 是否可以改变裁剪框的尺寸 默认true
      background: false, //  是否在容器内显示网格状的背景
      movable: true // 是否可以移动图片 默认true
    })
    console.log(this.cropper)
  },
  methods: {
    onConfirm () {
      // console.log(this.cropper.getData())  这种方法可以把裁剪数据传给后端 让后端裁剪

      this.cropper.getCroppedCanvas().toBlob(async blob => {
        try {
          // 接口要求一个formdata的参数
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updateUserPhoto(formData)
          this.$emit('close')
          this.$emit('update-photo', data.data.photo)
          this.$toast.success('更新成功 ')
        } catch (error) {
          this.$toast.fail('头像更新失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
